package MainDemo;/**
 * @author XuXiaoK
 * @create 2020-01-21 14:29
 */

import com.netflix.config.ConfigurationManager;
import com.netflix.hystrix.HystrixCommand;
import com.netflix.hystrix.HystrixCommandGroupKey;
import com.netflix.hystrix.HystrixCommandProperties;

/**
 *@Author XiaoKe
 *@Date 2020/1/21 14:29
 *@Description TODO
 */
public class OpenTest {

    public static void main(String[] args) {
        // 断路器被强制打开
        ConfigurationManager.getConfigInstance().setProperty(
                "hystrix.command.default.metrics.rollingStats.timeInMilliseconds", 10000);
        ConfigurationManager.getConfigInstance().setProperty(
                "hystrix.command.default.metrics.circuitBreaker.requestVolumeThreshold", 10);
        ConfigurationManager.getConfigInstance().setProperty(
                "hystrix.command.default.metrics.circuitBreaker.errorThresholdPercentage", 50);
        for (int i = 0; i < 15; i++) {
            // 执行的命令全部都会超时
            MyCmmand cmmand = new MyCmmand();
            cmmand.execute();
            // 断路器打开后输出信息
            if (cmmand.isCircuitBreakerOpen()) {
                System.out.println("断路器打开，执行第" + (i + 1) + "个命令");
            }
        }
    }

    static class MyCmmand extends HystrixCommand<String> {

        // 设置超时的时间为500毫秒
        public MyCmmand() {
            super(Setter.withGroupKey(HystrixCommandGroupKey.Factory.asKey("ExampleGroup"))
                    .andCommandPropertiesDefaults(HystrixCommandProperties.Setter()
                            .withExecutionTimeoutInMilliseconds(500)));

        }

        protected String run() throws Exception {

            //Thread.sleep(800);
            return "";
        }

        @Override
        protected String getFallback() {

            return "";
        }
    }
}
